package com.fanwei.afgorithm.code2;

/**
 *
 * @author fanwei
 */
public class AddTwoNumbers {

    static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    static class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            if (l1 == null && l2 == null) return null;
            ListNode head = new ListNode(0);
            ListNode curr = head;
            int addOne = 0;
            while (!(l1 == null && l2 == null && addOne == 0)){
                int sum = addOne;
                sum += l1 == null? 0: l1.val;
                sum += l2 == null? 0: l2.val;
                addOne = sum > 9 ? 1: 0;

                curr.next = new ListNode(sum % 10);
                curr = curr.next;

                if (l1 != null) l1=l1.next;
                if (l2 != null) l2=l2.next;
            }
            return head.next;
        }
    }

    public static void main(String[] args) {
        ListNode l1 = createListNode(2,3,4);
        ListNode l2 = createListNode(5,6,4);
        printNode(new Solution().addTwoNumbers(l1,l2));
    }

    public static ListNode createListNode(int ... x){
        ListNode l = new ListNode(0);
        ListNode node = l;
        for (int i : x){
            node.next = new ListNode(i);
            node = node.next;
        }
        return l.next;
    }


    public static void printNode(ListNode l){
        StringBuilder builder = new StringBuilder();
        while (l != null){
            builder.append(l.val);
            l = l.next;
        }
        System.out.println(builder.toString());
    }
}
